const path = require('path');
const qiniu = require('qiniu');
const fs = require('fs');
/* eslint-disable */
const isFile = function (file) {
  return file && file.indexOf('.') > 0;
};

// TEST
qiniu.conf.ACCESS_KEY = 'KvJPnxNg262bz4IA-5s0DUtj07cmkyLtv56nmEy_';
qiniu.conf.SECRET_KEY = 'iCXre_oKJU8QFWc52h5cUny9deqnN4920k6-8-dI';

// 要上传的空间
const bucket = 'xinzhiyun';

class QiniuUpload {
  constructor(localPath, remoteFileName) {
    this.localPath = localPath;
    this.remoteFileName = remoteFileName;
    this.uptoken = this.uptoken();
  }

  uptoken() {
    console.log(bucket + ":" + this.remoteFileName+"||==");
    var putPolicy = new qiniu.rs.PutPolicy(bucket + ":" + this.remoteFileName);
    return putPolicy.token();
  }

  uploadFile() {
    console.log('start uploading......[' + this.localPath + '];[' + this.remoteFileName + ']');
    var extra = new qiniu.io.PutExtra();
    qiniu.io.putFile(this.uptoken, this.remoteFileName, this.localPath, extra, function (err, ret) {
      if (!err) {
        // 上传成功， 处理返回值
        console.log(ret.hash, ret.key, ret.persistentId);
      } else {
        // 上传失败， 处理返回代码
        console.log(err);
      }
    });
  }
}

const root = path.resolve(process.cwd(), 'build');
const uploadPath = '';

const iteratorFile = function (localFolder, remoteFolder) {
  fs.readdir(localFolder, function (err, files) {
    if (!files) {
      console.log('---------------------------------------------------')
      console.log(`localFolder:${localFolder};remoteFolder:${remoteFolder}`)
      console.log('dist目录不存在，构建失败，请查看日志并重新构建！')
      console.log('---------------------------------------------------')
      return;
    }
    files.map(file => {
      const localPath = path.resolve(localFolder, file);
      const remoteFileName = remoteFolder && remoteFolder.length > 0 ? remoteFolder + '/' + file : file;
      if (isFile(file)) {
        const upload = new QiniuUpload(localPath, remoteFileName);
        upload.uploadFile();
      } else {
        //循环文件夹
        iteratorFile(localPath, remoteFileName);
      }
    });
  });
}

iteratorFile(root, uploadPath);
